< previous page page_326 next page >

Page 326
number and type of parameters. The Declare statement provides this information to your Visual Basic application. If your declaration is incorrect, you are going to run into problems.
Consider a DLL function, called MyDLLFunction, which takes two Long parameters. The correct declaration for this function would be
Private Declare Function MyDLLFunction Lib "mylibrary.dll" (ByVal A As _
Long, ByVal B As Long) As Long
What happens if you leave off the second parameter and declare the function as follows?
Private Declare Function MyDLLFunction Lib "mylibrary.dll" _
(ByVal A As Long) As Long
Figure T4-6a shows two stack frames. The one on the left shows the stack frame as it was actually called (with only one parameter). The one on the right shows the stack frame the DLL function actually expected. What happens if the DLL function uses parameter B? It tries to access the location that it believes should contain the parameter, but the calling function never pushed a value onto the stack. As a result, the DLL function sees some undetermined value. It might be a local variable from the prior stack frame. It might be another value stored on the stack. It certainly won't be what the function expects to see.
A more serious problem can be seen in Figure T4-6b. This figure shows what happens when the function returns. The DLL function is responsible for popping the parameters from the stack. It thinks that both parameters are there, so it naturally pops both of them from the stack. This means that the stack pointer is not restored to the value it had before the function was called. If this were a C program, you would be looking at an almost-certain memory exception at this point.
Visual Basic, however, has an added level of protection. Before it calls a DLL function, it stores the value of the stack pointer. When the DLL function returns, Visual Basic checks to see if the stack pointer has been restored to the original value. If it has not, it raises the following error:
Runtime Error 49
Bad DLL Calling Convention Error.
which is where this tutorial started in the first place.
This error always means that your Declare statement is incorrect and that the error was caused by a stack pointer misalignment when the DLL or API function returned.
What can cause this type of misalignment?

 
< previous page page_326 next page >